'use client'

import { useState, useEffect } from 'react'
import DataSourceFilter from '@/components/data-source-filter'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'

interface Parameter {
  id: number
  parameter_name: string
  data_type: string
  data_source: string
  is_required: boolean
  measurement_class: string
  example_description: string
}

export default function TestFilterPage() {
  const [parameters, setParameters] = useState<Parameter[]>([])
  const [dataSourceFilter, setDataSourceFilter] = useState<string>('all')
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchParameters = async () => {
      try {
        const res = await fetch('/api/sqlite-parameters?deviceId=1&type=base')
        const data = await res.json()
        setParameters(data)
      } catch (error) {
        console.error('获取参数失败:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchParameters()
  }, [])

  // 根据数据来源筛选参数
  const filteredParameters = parameters.filter(param => {
    if (dataSourceFilter === 'all') return true
    return param.data_source === dataSourceFilter
  })

  if (loading) {
    return (
      <div className="container mx-auto py-6">
        <div className="text-center">加载中...</div>
      </div>
    )
  }

  return (
    <div className="container mx-auto py-6 space-y-6">
      <div>
        <h1 className="text-2xl font-bold mb-2">数据来源筛选测试</h1>
        <p className="text-gray-600">测试设备参数的数据来源筛选功能</p>
      </div>

      {/* 筛选组件 */}
      <DataSourceFilter
        currentFilter={dataSourceFilter}
        onFilterChange={setDataSourceFilter}
        parameters={parameters}
      />

      {/* 参数列表 */}
      <Card>
        <CardHeader>
          <CardTitle>
            参数列表 ({filteredParameters.length} / {parameters.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {filteredParameters.map((param) => (
              <div
                key={param.id}
                className="flex items-center justify-between p-3 border rounded-lg"
              >
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <span className="font-medium">{param.parameter_name}</span>
                    {param.is_required && (
                      <Badge variant="destructive" className="text-xs">必填</Badge>
                    )}
                  </div>
                  <div className="text-sm text-gray-600 mt-1">
                    {param.example_description !== '—' && param.example_description}
                  </div>
                </div>
                
                <div className="flex items-center gap-3 text-sm">
                  <div className="text-center">
                    <div className="text-xs text-gray-500">数据类型</div>
                    <div className="font-medium">{param.data_type}</div>
                  </div>
                  
                  {param.measurement_class !== '—' && (
                    <div className="text-center">
                      <div className="text-xs text-gray-500">计量类</div>
                      <div className="font-medium">{param.measurement_class}</div>
                    </div>
                  )}
                  
                  <div className="text-center">
                    <div className="text-xs text-gray-500">数据来源</div>
                    <Badge 
                      variant={param.data_source === 'P' ? 'default' : 'outline'}
                      className="font-medium"
                    >
                      {param.data_source}
                    </Badge>
                  </div>
                </div>
              </div>
            ))}
          </div>
          
          {filteredParameters.length === 0 && (
            <div className="text-center py-8 text-gray-500">
              没有找到符合条件的参数
            </div>
          )}
        </CardContent>
      </Card>

      {/* 统计信息 */}
      <Card>
        <CardHeader>
          <CardTitle>统计信息</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {['P', 'E', 'M', 'O'].map(source => {
              const count = parameters.filter(p => p.data_source === source).length
              const percentage = parameters.length > 0 ? Math.round((count / parameters.length) * 100) : 0
              
              return (
                <div key={source} className="text-center p-4 bg-gray-50 rounded-lg">
                  <div className="text-2xl font-bold text-blue-600">{count}</div>
                  <div className="text-sm font-medium">
                    {source === 'P' && '采购数据'}
                    {source === 'E' && '工程数据'}
                    {source === 'M' && '制造数据'}
                    {source === 'O' && '运维数据'}
                  </div>
                  <div className="text-xs text-gray-500">{percentage}%</div>
                </div>
              )
            })}
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
